package com.ysd.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ysd.entity.Admin;

//Filter过滤器
public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	//doFilter 是过滤的核心方法 访问所有请求都会经过该方法 所以只需要在该方法中判断用户有没有登陆过即可
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest req =(HttpServletRequest) request;//ServletRequest强转为HttpServletRequest
		HttpServletResponse res = (HttpServletResponse)response;//ServletResponse 强转为  HttpServletResponse
		
		HttpSession session=req.getSession();//创建session对象
		Admin admin = (Admin)   session.getAttribute("admin");
		
		String url=req.getRequestURI();
		System.out.println(url);
		if (url.endsWith(".css")||url.endsWith(".js")||url.endsWith(".jpg")) {//访问静态资源放行
			chain.doFilter(req, res);
		}else if (url.indexOf("login.html")>0) {//代表访问的是登陆页面
			chain.doFilter(req, res);
		}else {//代表访问的不是登陆页面
			if (admin!=null) {//登陆过
				chain.doFilter(req, res);
			} else {//没有登陆过
					res.sendRedirect("/qiuxieshangcheng/admin/login.html");//重定向
					//绝对路径 相对路径
					//前面加/ 代表绝对巨鲸，会完全按照写的路径去访问页面
					// 相对路径： 路径前无"/" 代表是相对路径，相对路径是相对于本文件的地址去访问
			}
		}
		
		
		
		
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}
	
	
	
}
